<template>
  <el-dialog v-model="visible" :title="title">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="6em">
      <el-form-item label="区域代理" prop="agent">
        <el-select v-model="form.agent" placeholder="请选择区域代理">
          <el-option
            v-for="item in agentStore.list"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户" prop="referrer">
        <el-select v-model="form.referrer" placeholder="请选择用户">
          <el-option
            v-for="item in userProfileStore.list"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="areas">
        <city-select v-model="selectCityIds" :multiple="false" emitPath />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="输入名称" />
      </el-form-item>
      <el-form-item label="联系名称" prop="contact_name">
        <el-input v-model="form.contact_name" placeholder="输入联系名称" />
      </el-form-item>
      <el-form-item label="联系电话" prop="contact_phone">
        <el-input v-model="form.contact_phone" placeholder="输入联系电话" />
      </el-form-item>
      <el-form-item label="是否有效" prop="is_active">
        <el-switch v-model="form.is_active" />
      </el-form-item>
      <el-form-item label="商户图片" prop="store_image">
        <el-upload
          list-type="picture-card"
          :file-list="fileList"
          :limit="1"
          :auto-upload="false"
          :on-change="handleChange"
          :before-remove="handleRemove"
        >
          <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="merchantStore.loading.create || merchantStore.loading.update"
          @click="handleConfirm"
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { defineModel } from "vue";
import { useMerchantStoreHook } from "@/store/modules/merchant/merchant";
import { MerchantForm } from "@/api/merchant/merchant";
import { useAgentStoreHook } from "@/store/modules/agent/agent";
import { useUserProfileStoreHook } from "@/store/modules/user/profile";
import { UploadFile, UploadFiles } from "element-plus";
import { getImageFileFromUrl } from "@/utils";

const merchantStore = useMerchantStoreHook();

const agentStore = useAgentStoreHook();

const userProfileStore = useUserProfileStoreHook();

export type FormType = "add" | "edit";

export interface Props {
  type: FormType;
  form?: MerchantForm;
}

const visible = defineModel({ type: Boolean, default: false });

const emits = defineEmits(["confirm"]);

const props = defineProps<Props>();

const formRef = ref();

const form = reactive<Partial<MerchantForm>>({
  name: "",
});

const selectCityIds = ref<number[]>([]);

const fileList = ref<any>([]);

const rules = {
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: "change",
    },
  ],
  referrer: [
    {
      required: true,
      message: "请选择用户",
      trigger: "change",
    },
  ],
  areas: [
    {
      required: true,
      message: "请选择区域",
      trigger: "change",
      validator: (rule: any, value: any, callback: any) => {
        if (selectCityIds.value.length === 0) {
          callback(new Error("请选择区域"));
        }
        callback();
      },
    },
  ],
  contact_name: [
    {
      required: true,
      message: "请输入联系名称",
      trigger: "change",
    },
  ],
  contact_phone: [
    {
      required: true,
      message: "请输入联系电话",
      trigger: "change",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的联系电话",
      trigger: "change",
    },
  ],
  store_image: [
    {
      required: true,
      message: "请上传图片",
      trigger: "change",
    },
  ],
};

const title = computed(() => {
  return props.type === "add" ? "新增" : "编辑";
});

watch(visible, async (val) => {
  if (val) {
    await agentStore.fetchList({ page: 1, size: 1000, search: "" });
    await userProfileStore.fetchUserProfileList({ page: 1, size: 1000 });
    if (props.type === "edit") {
      fileList.value.push({ uid: Date.now(), url: props.form!.store_image });
      const idKeys: (keyof MerchantForm)[] = ["province", "city", "district"];
      idKeys.forEach((key) => {
        if (props.form?.[key]) {
          selectCityIds.value.push(props.form?.[key] as number);
        }
      });
      Object.assign(form, props.form);
      const file = await getImageFileFromUrl(props.form!.store_image!, "image.png");
      form.store_image = file as unknown as string;
    }
  } else {
    selectCityIds.value = [];
    formRef.value.resetFields();
    fileList.value = [];
  }
});

function handleChange(e: UploadFile) {
  console.log(e);
  fileList.value.push(e.raw!);
  form.store_image = URL.createObjectURL(e.raw!);
}

function handleRemove(e: UploadFile, es: UploadFiles) {
  form.store_image = "";
  return true;
}

function handleConfirm() {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (props.type === "add") {
        await merchantStore.fetchCreateMerchant(form);
      } else {
        await merchantStore.fetchUpdateMerchant(form);
      }
      visible.value = false;
      emits("confirm");
    }
  });
}
</script>

<style scoped lang="scss"></style>
